package com.xiaochong.kz.config.mysql;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * springBoot集成Mybatis的入口
 * Created by cx on 2017/9/23.
 */
@Configuration
@MapperScan(basePackages = "com.xiaochong.kz.dao" , sqlSessionFactoryRef = "sqlSessionFactory")
public class MybatisConfig {

    @Value("${mybatis.type-aliases-package}")
	private String alpackage;

	@Value("${mybatis.mapper-locations}")
	private String locations;

	

	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource, PageHelper pageHelper) throws Exception{
		SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
		fb.setDataSource(dataSource);
		fb.setTypeAliasesPackage(alpackage);// 指定基包
		fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(locations));
		fb.setPlugins(new Interceptor[]{pageHelper});
		return fb.getObject();
	}

	@Bean
	public PageHelper pageHelper() {
		PageHelper pageHelper = new PageHelper();
		Properties p = new Properties();
		p.setProperty("offsetAsPageNum", "true");
		p.setProperty("rowBoundsWithCount", "true");
		p.setProperty("reasonable", "true");
		p.setProperty("dialect", "mysql");
		pageHelper.setProperties(p);
		return pageHelper;
	}


}
